package security.keyManagement;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.bouncycastle.jce.provider.JCERSAPrivateCrtKey;
import org.bouncycastle.openssl.PEMReader;

public class Utils {

	public static java.security.cert.X509Certificate getX509CertFromFile(String filename){

		InputStream inStream;
		try {
			inStream = new FileInputStream(filename);
			CertificateFactory cf = CertificateFactory.getInstance("X.509");
			X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
			inStream.close();

			return cert;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (CertificateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	public static javax.security.cert.X509Certificate getReadableX509CertFromFile(String filename){


		try {
			FileInputStream fis = new FileInputStream(filename);			
			javax.security.cert.X509Certificate x509Certificate = javax.security.cert.X509Certificate.getInstance(fis);

			return x509Certificate;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (javax.security.cert.CertificateException e) {
			e.printStackTrace();
		}
		return null;

	}

	public static javax.security.cert.X509Certificate getReadableX509Certificate(Certificate certificate){

		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(certificate.getEncoded());
			javax.security.cert.X509Certificate x509Certificate = javax.security.cert.X509Certificate.getInstance(bis);

			return x509Certificate;

		} catch (CertificateException e) {
			e.printStackTrace();
		} catch (javax.security.cert.CertificateException e) {
			e.printStackTrace();
		}
		return null;

	}
	
	public static PrivateKey getPrivateKeyFromFile(String filename){
		
		try {
			FileReader file = new FileReader(filename);
			PEMReader reader = new PEMReader(file);

			return (JCERSAPrivateCrtKey) reader.readObject();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

		
	}

}
